package com.yupi.maker.generator;

import cn.hutool.core.io.FileUtil;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;

/**
 * <p>Title: 封装脚本文件</p>
 * <p>Description: 执行jar包</p>
 *
 * @author su.gd
 * @date 2024-01-02
 */
public class ScriptGenerator {

    public static void doGenerator(String outputPath, String jarPath) {
        // 生成 Linux 脚本
        StringBuffer sb = new StringBuffer();
        sb.append("#!/bin/bash").append("\n");
        sb.append(String.format("java -Dfile.encoding=utf-8 -jar %s \"$@\"", jarPath)).append("\n");
        FileUtil.writeBytes(sb.toString().getBytes(StandardCharsets.UTF_8), outputPath);
        // 添加可执行权限
        try {
            Set<PosixFilePermission> permissions = PosixFilePermissions.fromString("rwxrwxrwx");
            Files.setPosixFilePermissions(Paths.get(outputPath), permissions);
        } catch (Exception e) {
        }

        // 生成 Windows 脚本
        sb = new StringBuffer();
        sb.append("@echo off").append("\n");
        sb.append(String.format("java -Dfile.encoding=utf-8 -jar %s %%*", jarPath)).append("\n");
        FileUtil.writeBytes(sb.toString().getBytes(StandardCharsets.UTF_8), outputPath + ".bat");
    }
}
